package com.brsya.base.widget;

import static android.view.WindowManager.LayoutParams.MATCH_PARENT;

import android.content.Context;
import android.content.DialogInterface;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;

import com.brsya.base.R;


/**
 * 页面底部dialog
 * @author MLT
 */
public abstract class BottomDialog {
    private AlertDialog alertDialog;
    private View contentView;

    public BottomDialog(Context context) {
        this(context, R.style.dialog_lt);
    }

    public BottomDialog(@NonNull Context context, int themeResId) {
        alertDialog = new AlertDialog.Builder(context, themeResId).create();
        Window win = alertDialog.getWindow();
        win.setGravity(Gravity.BOTTOM);
        win.getDecorView().setPadding(0, 0, 0, 0);
        win.getAttributes().width = MATCH_PARENT;
        alertDialog.setCancelable(true);
        setKeyListener(true);
    }

    /**
     * 设置是否可点击返回或返回键返回
     */
    public void setKeyListener(final boolean isBack) {
        alertDialog.setCanceledOnTouchOutside(isBack);
        alertDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialogInterface, int i, KeyEvent keyEvent) {
                if (keyEvent.getAction() == KeyEvent.KEYCODE_BACK) {
                    if (isBack) {
                        alertDialog.dismiss();
                    }
                    return true;
                }
                return false;
            }
        });
    }

    public void show() {
        alertDialog.show();
        alertDialog.setContentView(contentView);
    }

    public void dismiss() {
        alertDialog.dismiss();
    }

    public void setContentView(View view) {
        contentView = view;
    }

    public Context getContext() {
        return alertDialog.getContext();
    }

}
